<script setup>
import {computed, ref, watch} from "vue";
import {useStore} from "vuex";
import {useRouter} from "vue-router";
import {ElMessage} from "element-plus";
import axios from "axios";

let props = defineProps({
   labelArr: Array,
   type: true,//true表示新增，false表示修改
})
let form = ref({
   name: "",
   tel: "",//电话
   rid: 0,
   id: 0,//
   tx: "",//头像
   rname:"",
   positionName:"",
   departmentName:""
})

const propKArr = computed(() => {
   if (!Array.isArray(props.labelArr)) {
      console.warn('props.labelArr is not an array');
      return [];
   }

   if (props.labelArr === undefined) {
      return [];
   }

   return props.labelArr.reduce((acc, label) => {
      const key = Object.keys(label)[0];
      acc[key] = label[key];
      return acc;
   }, {});
});


let store = useStore()
let show = computed(() => {
   return store.state.AEIsShow
})


function deleteForm() {
   store.commit("setShow", false)
   console.log(store.state.AEIsShow)
}



//-----------------------------------------------------------------
let lianDong = computed(() => {
   let temp = new Map();
   for (let i = 0; i < store.state.departmentArr.length; i++) {
      let did = store.state.departmentArr[i].did;
      let temp1 = [];
      for (let j = 0; j < store.state.positionArr.length; j++) {
         if (store.state.departmentArr[i].did === store.state.positionArr[j].did) {
            temp1.push(store.state.positionArr[j].rname);
         }
      }
      if (temp1.length > 0) {
         temp.set(did, temp1);
      } else {
         temp.set(did, []);
      }
   }
   return temp;
});
let selectedPosition = ref(null);
let selectedDepartment = ref(null);
let positionArr = ref([]);
let departmentArr = computed(() => {
   return store.state.departmentArr;
})
// 监听部门变化，更新职位选项
watch(selectedDepartment, (newVal) => {
   if (newVal !== null) {
      // 查找选中部门的ID
      const department = departmentArr.value.find(item => item.dname === newVal);
      if (department) {
         // 根据部门ID找到对应的职位数组
         positionArr.value = lianDong.value.get(department.did) || [];
         selectedPosition.value = null; // 重置职位选择
      }
   }
}, {immediate: true});

function handleDepartmentChange() {
   // 部门变化时，职位选择重置
   selectedPosition.value = null;
}
function handlePositionChange(newVal) {
  for (let i = 0; i < store.state.positionArr.length; i++) {
    if (store.state.positionArr[i].rname === newVal) {
      form.value.rid = store.state.positionArr[i].rid;
      console.log("rid:" + form.value.rid)
      break;
    }
  }
}
//--------------------------------------------------------------


const upData = () => {
   const formData = new FormData();
   formData.append('tx', document.getElementById('file').files[0]);
   axios.post('/file/upload', formData, {
      headers: {
         'Content-Type': 'multipart/form-data'
      }
   }).then(res => {
      form.value.tx = res.data.msg;
      console.log(res.data.msg)
   }).catch(err => {
      console.log(err)
   })
}

function editClick() {
   store.commit("setShow", false)
   console.log(form.value)
   if (props.type) {//新增
      axios.post("/addEmployeeInfo", form.value).then(res => {
         console.log(res)
         if (res.data.code === 200) {
            upData()
            ElMessage("添加成功")

         } else {
            ElMessage("添加失败")
         }
      }).catch(err => {
         console.log(err)
      })
   } else {//修改
      axios.put("/positionInfo/update", props.form).then(res => {
         console.log(res)
         if (res.data.code === 200) {
            ElMessage("修改成功")

         }
      }).catch(err => {
         console.log(err)
      })
   }
}
</script>

<template>
   <div class="home" v-show="show">
      <div class="content">
         <div class="form">
            <div class="row" v-for="(value, key) in propKArr" :key="key">
               <span>{{ value }}</span>
               <el-input class="input" v-model="form[key]" autocomplete="off"/>
            </div>
            <div class="row">
               <div>
                  <span>头像</span>
                  <input style="width: 350px;margin-left: 20px;border: none" id="file" type="file"/>
               </div>

               <div>
                  <span>部门</span>
                  <el-select style="width: 350px;margin-left: 20px;margin-top: 20px" v-model="selectedDepartment"
                             placeholder="请选择部门"
                             @change="handleDepartmentChange">
                     <el-option
                         v-for="item in departmentArr"
                         :key="item.did"
                         :label="item.dname"
                         :value="item.dname"
                     />
                  </el-select>
               </div>
               <div style="margin-top: 20px">
                  <span>职位</span>
                  <el-select style="width: 350px;margin-left: 20px" v-model="selectedPosition" placeholder="请选择职位"
                             @change="handlePositionChange"
                  >
                     <el-option
                         v-for="item in positionArr"
                         :key="item"
                         :label="item"
                         :value="item"
                     />
                  </el-select>
               </div>

            </div>
         </div>
         <div class="btn">
            <button
                style="height:25px;font-size: 14px;background-color: rgba(64,158,255,0.81);width: 100px;text-align:  center;cursor:pointer;border-radius: 10px;color: white;border: none;float: none"
                @click="deleteForm()">取消
            </button>

            <button
                style="height:25px;font-size: 14px;background-color: rgba(64,158,255,0.81);width: 100px;text-align:  center;cursor:pointer;border-radius: 10px;color: white;border: none;margin-left: 30px;float: none"
                @click="editClick()">确定
            </button>
         </div>
      </div>
   </div>
</template>

<style scoped>
.home {
   width: 100%;
   height: 100%;
   background-color: rgba(0, 0, 0, 0.2);
   position: absolute;
   top: 0;
   left: 0;
   z-index: 999;
}

.content {
   padding-top: 30px;
   padding-bottom: 70px;
   width: 500px;
   background-color: white;
   position: relative;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
   border-radius: 10px;
}

.form {
   margin-top: 40px;
   margin-left: 20px;
   margin-right: 20px;
}

.row {
   margin-bottom: 20px;
}

.input {
   width: 350px;
   margin-left: 20px;
}

.btn {
   position: absolute;
   bottom: 20px;
   right: 20px;
   margin-top: 40px;
   margin-left: 20px;
   margin-right: 20px;
}

</style>